import Vue from 'vue';
import Vuex from 'vuex';
import { freeRequest, executeQueue } from '@/common/xhr.js';
import request from '@/common/request.js';

import home from '@/home/store/index.js';
import activity from '@/activity/store/index.js';
import interaction from '@/interaction/store/index.js';
import personal from '@/activity/store/index.js';
import diary from './diary.js';
import houseSetting from '../houseSetting/store/index.js'

Vue.use(Vuex);
const state = {
	userInfo: uni.getStorageSync('userInfo') || {},
	loginStatus: !!uni.getStorageSync('Authorization'),
	Authorization: uni.getStorageSync('Authorization') || '',
	location: uni.getStorageSync('location') || {},
	currentHouse: uni.getStorageSync('currentHouse') || {},
	scene: uni.getStorageSync('scene') || '', //分享记录
	userSource: uni.getStorageSync('userSource') || '' //臻心来源
}


const actions = {
	wxLogin(context) { //小程序登录
		//#ifdef MP-WEIXIN
		//微信登陆，获取code、sessionkey、openid，uniapp开发时需注释
		return new Promise((resolve, reject) => {
			uni.login({
				success: res => {
					if (res.code) {
						//微信登录成功 已拿到code
						resolve(res.code);
					} else {
						reject(res.errMsg);
					}
				}
			})
		}).catch(res => {
			throw res;
		});
		//#endif
	},
	loginByCode({ commit, state }, { code, mobile = '', unionId = '' }) {
		const userInfo = { ...state.userInfo };
		return freeRequest('api/getUserByCode?code=' + code + '&phoneNumber=' + mobile + '&unionId=' + unionId, {
			method: 'get',
		}).then(result => {
			const { user = {}, token } = result;
			Object.assign(userInfo, user);
			commit('UPDATE_USERINFO', userInfo);
			commit('UPDATE_LOGINSTATUS', !!token);
			commit('UPDATE_AUTHORIZATION', token);
			executeQueue();
			return true;
		}).catch(res => {
			throw res;
		});
	},

	appLogin(context, data = {}) { //app端通过手机号登录
		return freeRequest('/api/appLogin', {
			method: 'POST',
			data,
			ContentType: 'application/x-www-form-urlencoded'
		}).then(result => {
			const {
				user: userInfo = {},
				token,
				code,
				msg
			} = result;
			if (code == 200) {
				context.commit('UPDATE_USERINFO', userInfo);
				context.commit('UPDATE_LOGINSTATUS', !!token);
				context.commit('UPDATE_AUTHORIZATION', token);
				executeQueue();
			}
			return result;
		}).catch(res => {
			throw res;
		});
	},
	getPhoneNumber(context, data = {}) { //获取手机号，并登陆
		let uid = context.state.scene || '';
		let userSource = context.state.userSource || '';
		if (userSource) {
			data.userSource = userSource;
		}
		return freeRequest('/api/login?' + uid, {
			method: 'POST',
			data,
			ContentType: 'application/x-www-form-urlencoded'
		}).then(result => {
			const {
				user: userInfo = {},
				token,
				code,
				msg
			} = result;
			if (code == 200) {
				context.commit('UPDATE_USERINFO', userInfo);
				context.commit('UPDATE_LOGINSTATUS', !!token);
				uni.setStorageSync('Authorization', token);
				uni.removeStorageSync('scene') //移出分享记录
				uni.removeStorageSync('userSource') //移出臻心
				executeQueue();
			}
			return result;
		}).catch(res => {
			throw res;
		});
	},
	getWxUserProfile(context, { avatarUrl, nickName }) { //获取小程序用户信息
		return new Promise(resolve => {
			const userInfo = {
				...context.state.userInfo
			};
			const {
				userId
			} = userInfo;
			const data = {
				userId,
				avatar: avatarUrl,
				nickName: nickName
			};
			request('/api/cusUserInfo', {
				data,
				method: 'PUT'
			}).then(res => {
				if (res.code === 200) {
					Object.assign(userInfo, data);
					context.commit('UPDATE_USERINFO', userInfo);
					resolve();
				}
			}).catch(res => {
				throw res;
			});
		}).catch(res => {
			throw res;
		});
	},
	getLoginUserInfo({ state, commit }) {
		const userInfo = { ...state.userInfo };
		return request('/api/cusUserInfo/getUserInfo', {
			method: 'GET'
		}).then(res => {
			if (res.code === 200) {
				Object.assign(userInfo, res.data || {});
				commit('UPDATE_USERINFO', userInfo);
				return userInfo;
			}
		}).catch(res => {
			throw res;
		});
	},
	getLocationByGPS(context, {
		latitude,
		longitude
	}) {
		return request('/api/cusCityInfo/getCurrentCity', {
			data: {
				latitude,
				longitude
			},
			method: 'GET'
		}).then(result => {
			const {
				data,
				hisCity,
				code
			} = result;
			const location = data || hisCity
			if (location) {
				context.commit('UPDATE_LOCATION', location);
			}
			return location;
		}).catch(res => {
			throw res;
		});
	}
}

const mutations = {
	UPDATE_USERINFO(state, userInfo) { //更新用户信息
		state.userInfo = Object.assign({}, state.userInfo, {
			...userInfo
		});
		uni.setStorageSync('userInfo', state.userInfo);
	},
	UPDATE_LOGINSTATUS(state, status) { //更新登录信息
		state.loginStatus = status;
	},
	UPDATE_LOCATION(state, location) { //更新位置信息
		state.location = Object.assign({}, state.location, {
			...location
		});
		uni.setStorageSync('location', state.location);
	},
	UPDATE_CURRENTHOUSE(state, currentHouse) { //更新当前房屋信息
		state.currentHouse = Object.assign({}, state, {
			...currentHouse
		});
		uni.setStorageSync('currentHouse', state.currentHouse);
	},
	UPDATE_AUTHORIZATION(state, token) { //更新接口令牌
		state.Authorization = token;
		uni.setStorageSync('Authorization', token);
	},
	STORE_SCENE(state, scene) { // 保存code
		// state.scene = scene.slice(4);
		state.scene = scene
		uni.setStorageSync('scene', state.scene);
	},
	STORE_USERSOURCE(state, userSource) { // 保存臻心来源
		state.userSource = userSource
		uni.setStorageSync('userSource', state.userSource);
	}
}

const getters = {}

const store = new Vuex.Store({
	state,
	actions,
	mutations,
	getters,
	modules: {
		home,
		activity,
		interaction,
		personal,
		diary,
		houseSetting
	}
});
export default store
